<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 本地图片代理服务 - 解决CORS跨域问题
 * 尊重劳动成果是一种美德
 */

// 设置CORS头，允许跨域访问
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: *');

// 处理OPTIONS预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// 获取图片ID
$imageId = isset($_GET['id']) ? urldecode($_GET['id']) : '';

if (empty($imageId)) {
    http_response_code(400);
    echo 'Missing image ID';
    exit;
}

// 转发请求到H3yunApi的图片代理（请替换为您的实际域名）
$h3yunApiUrl = 'https://your-domain.com/api/image_proxy.php?id=' . urlencode($imageId);

// 使用cURL获取图片
$ch = curl_init($h3yunApiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头

// 执行请求
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$curlError = curl_error($ch);
curl_close($ch);

// 检查是否成功
if ($httpCode !== 200 || empty($response)) {
    http_response_code(404);
    echo 'Image not found';
    exit;
}

// 分离响应头和响应体
$responseHeader = substr($response, 0, $headerSize);
$responseBody = substr($response, $headerSize);

// 解析Content-Type
preg_match('/Content-Type:\s*([^\r\n]+)/i', $responseHeader, $typeMatches);
$contentType = $typeMatches[1] ?? 'image/jpeg';

// 返回图片
header('Content-Type: ' . $contentType);
header('Cache-Control: public, max-age=86400'); // 缓存1天
header('Content-Length: ' . strlen($responseBody));

echo $responseBody;
